package com.imay.live.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.CallSuper;
import android.support.v4.app.ActivityCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.helper.ActivityHelper;
import com.imay.base.helper.NetworkHelper;
import com.imay.base.manager.ActivityStackManager;
import com.imay.base.util.NetworkUtil;
import com.imay.base.util.StringUtil;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.cocos.IMayCocos;
import com.imay.cocos.IMayCocosNetManager;
import com.imay.live.activity.recharge.RechargeActivity;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.fragment.PopupMenuFragment;
import com.imay.live.fragment.room.ChooseUserFragment;
import com.imay.live.fragment.room.InfoCardFragment;
import com.imay.live.fragment.room.LiveRecordFragment;
import com.imay.live.fragment.room.ScreenshotFragment;
import com.imay.live.helper.CallBack;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.H5Helper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.helper.RoomNoticeHelper;
import com.imay.live.helper.ShareSDKHelper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.helper.UrlHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.UploadFileManager;
import com.imay.live.media.LivePlayer;
import com.imay.live.media.LivePusher;
import com.imay.live.model.AdsModel;
import com.imay.live.model.CocosOpenWebViewModel;
import com.imay.live.model.DeviceInfoModel;
import com.imay.live.model.DiamonNotityModel;
import com.imay.live.model.MenuItemModel;
import com.imay.live.model.SysparamModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.MessageId;
import com.imay.live.proto.ReportCategory;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequest;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.proto.helper.ProtoRequestParams;
import com.imay.live.proto.helper.ProtoSocketFactory;
import com.imay.live.proto.room.RoomActivityTipsNotify;
import com.imay.live.proto.room.RoomChatNotify;
import com.imay.live.proto.room.RoomGameHostAgreeInviteNotify;
import com.imay.live.proto.room.RoomGameHostRefuseInviteNotify;
import com.imay.live.proto.room.RoomGameInviteNotify;
import com.imay.live.proto.room.RoomHouseNotify;
import com.imay.live.proto.room.RoomKickUserNotify;
import com.imay.live.proto.room.RoomLikeNotify;
import com.imay.live.proto.room.RoomListUserResp;
import com.imay.live.proto.room.RoomLiveBlockNotify;
import com.imay.live.proto.room.RoomRankUpgradeNotify;
import com.imay.live.proto.room.RoomSendGiftNotify;
import com.imay.live.proto.room.RoomSetAdminNotify;
import com.imay.live.proto.room.RoomSilenceUserNotify;
import com.imay.live.proto.room.RoomUserCountUpdateNotify;
import com.imay.live.proto.room.RoomUserListUpdateNotify;
import com.imay.live.proto.sns.SnsFollowUserResp;
import com.imay.live.proto.user.UserInfoCard;
import com.imay.live.proto.user.UserMoneyUpdateNotify;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.ImayLogUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.custom.LiveVideoView;
import com.imay.live.view.custom.RoomBaseView;
import com.imay.live.view.custom.RoomLiveNormalView;
import com.imay.live.view.dialog.ShareDialogFragment;
import com.imay.live.R;
import com.imay.live.view.dialog.ShowAdsFragment;
import com.imay.tbas_api.IMYTBASObject;
import com.imay.tsnackbar.TSnackbar;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.umeng.socialize.UMShareAPI;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static com.imay.live.params.IMParams.CONFIG_SWITCH_RECHARGE_TIP;
import static com.imay.live.params.IMParams.CONFIG_VALUE_RECHARGE_TIP_URL2;
import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by jeaman on 2017/3/17.
 */

public abstract class RoomBaseActivity extends BaseCocosActivity implements LivePusher.PushListener, LivePlayer.PlayListener,
        RoomBaseView.OnActionListener, InfoCardFragment.OnInfoCardClickListener, PopupMenuFragment.OnMenuClickListener,
        NetworkHelper.NetworkStateListener, IMayCocosNetManager.OnCocosRoomListener,
        ChooseUserFragment.OnChooseUserListener, LiveRecordFragment.OnLiveRecordListener, ShareSDKHelper.ShareCallBack {

    private final static String TAG = RoomBaseActivity.class.getSimpleName();
    private final static int REQUEST_CODE_SCREEN_SHOT = 1024;
    private final static int REQUEST_CODE_SCREEN_SHOT_REPOST = 1025;
    protected final static String FRAGMENT_TAG_MANAGER_MENU = "manager_menu";
    private final static String PUSH_DISCONNECT_TAG = "PUSH_DISCONNECT";

    //菜单action
    protected final static int MENU_ACTION_INFORM = 100;
    protected final static int MENU_ACTION_SILENCE = 101;
    protected final static int MENU_ACTION_KICK = 102;
    protected final static int MENU_ACTION_BLACK = 103;
    private final static int MENU_ACTION_REPORT_OBSCENE = 201;
    private final static int MENU_ACTION_REPORT_FRAUD = 202;
    private final static int MENU_ACTION_REPORT_VIOLENCE = 203;
    private final static int MENU_ACTION_REPORT_DRUG = 204;
    private final static int MENU_ACTION_REPORT_UNLIKE = 205;

    //cocos点击事件id
    private final static int COCOS_CLICK_ID_SWITCH_CAMERA = 1;  //连麦切换摄像头
    private final static int COCOS_CLICK_ID_CLOSE_LINE_MIC = 2; //连麦关闭

    private final static int USER_PAGE_SIZE = 10;   //用户列表每页数量
    private final static int PERMISSION_REQUEST_CODE_CAMERA = 1;
    private final static int PERMISSION_REQUEST_CODE_AUDIO_RECORD = 2;

    private ArrayList<MenuItemModel> mInformMenuList = new ArrayList<>();
    private ArrayList<MenuItemModel> mReportCategoryMenuList = new ArrayList<>();
    protected UserInfoCard mMenuActionUser;    //菜单操作的用户id

    protected RoomBaseView mRoomView;
    protected LiveVideoView mLiveVideoView;

    protected LivePlayer mLivePlayer;
    protected LivePusher mLivePusher;

    protected String mPushUrl;
    protected String mStreamUrl;    //普通拉流地址
    protected String mLinkMicStreamUrl; //连麦时快速拉流地址

    // 关注系统设置项“自动旋转”的状态切换
    private RotationObserver mRotationObserver = null;

    protected boolean mStartPush = false;
    protected long mRoomId;
    private IMYTBASObject mSocketNotify;    //socket消息监听
    private IMYTBASObject mLoginNotify; //登录成功监听
    private IMYTBASObject mFollowNotify; //关注监听
    private IMYTBASObject mUnFollowNotify; //取消关注监听

    private boolean mWaitCheckCameraPermission;   //点击设置后，检查相机权限

    private boolean mPausePush;  //是否暂停推流
    private boolean mPausePlay;  //是否暂停播放
    private boolean mLinkMicMode;   //当前是否连麦状态

    //请求开播信息和推流地址成功了才允许开播
    protected UserInfoCard mAnchorInfo;   //主播信息
    protected boolean mAdmin;   //自己是否管理员
    private boolean mCocosExitRoom;
    //适用于发送socket 请求
    protected boolean mHasFollowed;//是否已经关注过
    protected boolean mHasShared;//是否已经分享过
    private boolean mCocosAllowClose = true;//cocos 设置是否可以关闭房间
    private Runnable mResumeAllowCloseRunnable;


    private static AtomicInteger oneScreenshot = new AtomicInteger(0);
    private MediaProjectionManager mMediaProjectionManager;
    private Handler mBackgroundHandler;
    private int mWidth;
    private int mHeight;
    private int mScreenDensity;
    private long mScreenShotTime;

    private int mReportCategory;
    protected int SCREENSHOT_SHARE = 1;
    protected int SCREENSHOT_REPORT = 2;

    protected void registerNotify() {
        registerSocketNotify();
        registerLoginNotify();
        registerFollowNotify();
        registerUnFollowNotify();
        //监听网络
        NetworkHelper.getInstance().addListener(this);
        //屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected boolean isSetDecorViewBackground() {
        return false;
    }

    @Override
    protected boolean useDynamicTitleBar() {
        return false;
    }

    //是否是大主播
    protected abstract boolean isMainPublisher();

    //是否需要发送推流状态
    protected boolean isNeedSendPushStatus() {
        return true;
    }

    //初始化推流
    protected void initPush(TXCloudVideoView videoView) {
        if (mLivePusher == null) {
            mLivePusher = new LivePusher(this, videoView);
            mLivePusher.setPushListener(this);
            //读取上次保存的美颜值
            int beautyLevel = PreferenceHelper.getInstance().getBeautyLevel(mLivePusher.getBeautyLevel());
            int whiteningLevel = PreferenceHelper.getInstance().getWhiteningLevel(mLivePusher.getWhiteningLevel());
            int ruddyLevel = PreferenceHelper.getInstance().getRuddyLevel(mLivePusher.getRuddyLevel());
            mLivePusher.setBeautyFilter(beautyLevel, whiteningLevel, ruddyLevel);

            if (isMainPublisher()) {
                mLivePusher.setNormalPublisher();
            } else {
                mLivePusher.setSubPublisher();
            }

            mRotationObserver = new RotationObserver(new Handler());
            mRotationObserver.startObserver();
        }
    }

    //初始化播放器
    protected void initPlayer(TXCloudVideoView videoView) {
        if (mLivePlayer == null) {
            mLivePlayer = new LivePlayer(this, videoView);
            mLivePlayer.setPlayListener(this);
        }
    }


    protected void initRoomView() {
        mRoomView = createRoomView();
        mRoomView.setUserPageSize(USER_PAGE_SIZE);
        mRoomView.setStatusBarHeight(getStatusBarHeight());
        mRoomView.setOnActionListener(this);
        mRoomView.attachKeyboard(RoomBaseActivity.this);

        onCocosSetLiveCloseEvent(false);
        addCocosView(mRoomView.getCocosContainer());
        IMayCocosNetManager.getInstance().addOnCocosRoomListener(this);

        initCommonMenu();
    }

    protected abstract RoomBaseView createRoomView();

    private void initCommonMenu() {

        mInformMenuList.add(new MenuItemModel(MENU_ACTION_INFORM, R.string.live_menu_inform));
//        mInformMenuList.add(new MenuItemModel(MENU_ACTION_BLACK, R.string.live_menu_black));

        mReportCategoryMenuList.add(new MenuItemModel(MENU_ACTION_REPORT_OBSCENE, R.string.report_category_obscene));
        mReportCategoryMenuList.add(new MenuItemModel(MENU_ACTION_REPORT_FRAUD, R.string.report_category_fraud));
        mReportCategoryMenuList.add(new MenuItemModel(MENU_ACTION_REPORT_VIOLENCE, R.string.report_category_violence));
        mReportCategoryMenuList.add(new MenuItemModel(MENU_ACTION_REPORT_DRUG, R.string.report_category_drug));
        mReportCategoryMenuList.add(new MenuItemModel(MENU_ACTION_REPORT_UNLIKE, R.string.report_category_unlike));
    }


    //登录成功
    protected void onLoginSuccess() {
//        if (mStartPush) {   //如果开始推流，继续推流
//            startPublishRtmp();
//        }
    }

    protected long getRoomId() {
        return mRoomId;
    }

    protected void setPushUrl(String pushUrl) {
        mPushUrl = pushUrl;
    }

    protected void setRoomId(long roomId) {
        mRoomId = roomId;
    }

    protected void setAnchorInfo(UserInfoCard anchorInfo) {
        mAnchorInfo = anchorInfo;
    }

    @CallSuper
    protected void startPublishRtmp() {
        mLivePusher.startPublishRtmp(mPushUrl);
        mStartPush = true;
    }

    @CallSuper
    protected void stopPublishRtmp() {
        mLivePusher.stopPublish();
        mStartPush = false;
    }

    @CallSuper
    protected void startPlay() {
        if (mPausePlay) {   //后台不播放
            return;
        }
        if (mLivePlayer != null) {
            mLivePlayer.startPlay();
        }
    }

    protected void switchCamera() {
        mLivePusher.switchCamera();
    }

    private void showUserInfoCard(final UserInfoCard user) {
        if (user == null) {
            return;
        }
        //显示用户资料卡
        boolean self = user.uid == AccountManager.getInstance().getUid();
        boolean isAnchor = mAnchorInfo != null && user.uid == mAnchorInfo.uid;
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), InfoCardFragment.newInstance(mRoomId, user, self, isMainPublisher(), isAnchor));
    }

    //关注
    private void requestFollowUser(final long uid, final CallBack callBack) {
        ProtoRequestHelper.task(ProtoSocketFactory.requestFollowUser(uid)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                SnsFollowUserResp resp = JSON.parseObject(data, SnsFollowUserResp.class);
                EventHelper.postFollowUser(resp.uid);
                updateFollowAnchorView(resp.uid, true);
                if (callBack != null) {
                    callBack.onSuccess();
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                if (code == ResultCode.CodeUserFollowExist) {   //已关注
                    updateFollowAnchorView(uid, true);
                } else {
                    ErrorResult.toastError(RoomBaseActivity.this, code);
                }
            }
        });
    }

    protected void updateFollowAnchorView(long uid, boolean isFollow) {
        if (mAnchorInfo != null && uid == mAnchorInfo.uid) {
            mRoomView.setFollowUser(isFollow);
        }
    }

    //获取房间公告
    protected void requestRoomTips() {
        if (mRoomView != null) {
            mRoomView.addChatMessage(RoomNoticeHelper.getInstance().getNotice());
            String nick = UserInfoCache.getNick();
            if (nick != null && !isMainPublisher()) {   //主播不显示自己进入房间
                mRoomView.addEnterRoomMessage(nick);
            }
        }
    }

    //用户列表加载更多请求
    private void requestLoadMoreUser(int page) {
        ProtoRequestHelper.task(ProtoSocketFactory.requestRoomUser(mRoomId, page, USER_PAGE_SIZE)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                RoomListUserResp resp = JSON.parseObject(data, RoomListUserResp.class);
                if (resp.users != null) {
                    mRoomView.addUserData(resp.users);
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                mRoomView.setUserLoadMoreFailed();
            }
        });
    }

    //处理公共的消息
    private void processCommonSocketNotify(int msgId, String content) {
        switch (msgId) {
            case MessageId.roomUserListUpdateNotify:    //用户列表更新
                final RoomUserListUpdateNotify roomUserListUpdateNotify = JSON.parseObject(content, RoomUserListUpdateNotify.class);
                //处理完数据再post到主线程更新ui
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomUserListUpdateNotify.roomId && mRoomView != null) {
                            mRoomView.setUserData(roomUserListUpdateNotify.users);
                            mRoomView.setUserNumber(roomUserListUpdateNotify.current);
                        }
                    }
                });
                break;
            case MessageId.roomUserCountUpdateNotify:   //在线人数
                final RoomUserCountUpdateNotify roomUserCountUpdateNotify = JSON.parseObject(content, RoomUserCountUpdateNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomUserCountUpdateNotify.roomId && mRoomView != null) {
                            mRoomView.setUserNumber(roomUserCountUpdateNotify.current);
                        }
                    }
                });
                break;
            case MessageId.roomChatNotify:  //聊天
                final RoomChatNotify roomChatNotify = JSON.parseObject(content, RoomChatNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomChatNotify.roomId && mRoomView != null) {
                            mRoomView.addChatMessage(roomChatNotify);
                        }
                    }
                });
                break;
            case MessageId.roomUserEnterNotify: //进入房间
//                final RoomUserEnterNotify roomUserEnterNotify = JSON.parseObject(content, RoomUserEnterNotify.class);
//                ThreadManager.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (getRoomId() == roomUserEnterNotify.roomId && mRoomView != null) {
//                            if (roomUserEnterNotify.user.uid != AccountManager.getInstance().getUid()) {
//                                mRoomView.addChatMessage(roomUserEnterNotify);
//                            }
//                        }
//                    }
//                });
                break;
            case MessageId.roomLikeNotify:  //点赞、关注、分享
                final RoomLikeNotify roomLikeNotify = JSON.parseObject(content, RoomLikeNotify.class);
                //第一次进入房间先显示
                if (roomLikeNotify.first) {
                    ThreadManager.post(new Runnable() {
                        @Override
                        public void run() {
                            if (getRoomId() == roomLikeNotify.roomId && roomLikeNotify.first && mRoomView != null) {
                                mRoomView.addChatMessage(roomLikeNotify);
                            }
                        }
                    });
                }
                break;
            case MessageId.roomSendGiftNotify:  //送礼物
                final RoomSendGiftNotify roomSendGiftNotify = JSON.parseObject(content, RoomSendGiftNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomSendGiftNotify.roomId && mRoomView != null) {
                            mRoomView.addChatMessage(roomSendGiftNotify);
                        }
                    }
                });
                break;
            case MessageId.roomKickUserNotify:  //踢人
                final RoomKickUserNotify roomKickUserNotify = JSON.parseObject(content, RoomKickUserNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (roomKickUserNotify.kickedUser.uid == AccountManager.getInstance().getUid()) {
                            ToastUtil.show(RoomBaseActivity.this, R.string.tips_kick);
                            finish();   //被踢，直接关闭界面
                        } else {
                            mRoomView.addChatMessage(roomKickUserNotify);
                        }
                    }
                });
                break;
            case MessageId.roomSilenceUserNotify:   //禁言
                final RoomSilenceUserNotify roomSilenceUserNotify = JSON.parseObject(content, RoomSilenceUserNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (roomSilenceUserNotify.kickedUser.uid == AccountManager.getInstance().getUid()) {
                            ToastUtil.show(RoomBaseActivity.this, R.string.tips_silence);
                        }
                        mRoomView.addChatMessage(roomSilenceUserNotify);
                    }
                });
                break;
            case MessageId.roomGameInviteNotify:    //游戏邀请
                final RoomGameInviteNotify roomGameInviteNotify = JSON.parseObject(content, RoomGameInviteNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomGameInviteNotify.RoomId && mRoomView != null) {
                            mRoomView.addChatMessage(roomGameInviteNotify);
                        }
                    }
                });
                break;
            case MessageId.roomGameHostAgreeInviteNotify:    //同意游戏邀请
                final RoomGameHostAgreeInviteNotify roomGameHostAgreeInviteNotify = JSON.parseObject(content, RoomGameHostAgreeInviteNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomGameHostAgreeInviteNotify.RoomId && mRoomView != null) {
                            mRoomView.addChatMessage(roomGameHostAgreeInviteNotify);
                        }
                    }
                });
                break;
            case MessageId.roomGameHostRefuseInviteNotify:    //拒绝游戏邀请
                final RoomGameHostRefuseInviteNotify roomGameHostRefuseInviteNotify = JSON.parseObject(content, RoomGameHostRefuseInviteNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomGameHostRefuseInviteNotify.RoomId && mRoomView != null) {
                            mRoomView.addChatMessage(roomGameHostRefuseInviteNotify);
                        }
                    }
                });
                break;
            case MessageId.roomRankUpgradeNotify:    //榜单提升通知
                final RoomRankUpgradeNotify roomRankUpgradeNotify = JSON.parseObject(content, RoomRankUpgradeNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomRankUpgradeNotify.roomId && mRoomView != null) {
                            mRoomView.addChatMessage(roomRankUpgradeNotify);
                        }
                    }
                });
                break;
            case MessageId.userMoneyUpdateNotify:   //魅力值
                final UserMoneyUpdateNotify userMoneyUpdateNotify = JSON.parseObject(content, UserMoneyUpdateNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mAnchorInfo != null && mAnchorInfo.uid == userMoneyUpdateNotify.uid && mRoomView != null) {
                            mRoomView.updateCharm(userMoneyUpdateNotify.meiliGain);
                        }
                    }
                });
                break;
            case MessageId.roomSetAdminNotify:  //设置管理员通知
                final RoomSetAdminNotify roomSetAdminReq = JSON.parseObject(content, RoomSetAdminNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (roomSetAdminReq.roomId == getRoomId() && roomSetAdminReq.uid == AccountManager.getInstance().getUid()) {
                            mAdmin = !roomSetAdminReq.remove;
                            ToastUtil.show(RoomBaseActivity.this, roomSetAdminReq.remove ? R.string.tips_admin_remove : R.string.tips_admin_set);
                        }
                    }
                });
                break;
            case MessageId.roomLinkStopNotify:  //结束连麦
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        onStopLinkMic();
                    }
                });
                break;
            case MessageId.roomLiveBlockNotify: //直播封禁通知
                final RoomLiveBlockNotify roomLiveBlockNotify = JSON.parseObject(content, RoomLiveBlockNotify.class);
                if (roomLiveBlockNotify.LockType != 3) {    //封房、封流
                    ThreadManager.post(new Runnable() {
                        @Override
                        public void run() {
                            onLiveBlock(roomLiveBlockNotify.uid);
                        }
                    });
                }
                break;
            case MessageId.roomHouseGoldUpdateNotify:
                if (!PreferenceHelper.getInstance().getRoomDiamonGuide()) {
                    final DiamonNotityModel diamonNotityModel = JSON.parseObject(content, DiamonNotityModel.class);
                    if (mRoomView instanceof RoomLiveNormalView) {
                        ThreadManager.post(new Runnable() {
                            @Override
                            public void run() {
                                ((RoomLiveNormalView) mRoomView).showDiamonGuide(RoomBaseActivity.this, diamonNotityModel.getGoldNum());
                                PreferenceHelper.getInstance().saveRoomDiamonGuide();
                            }
                        });
                    }
                }
//                Log.e("RICH",content);

                break;
            case MessageId.roomHouseCardSendNotify:
                final RoomHouseNotify roomHouseNotify = JSON.parseObject(content, RoomHouseNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomHouseNotify.roomId && mRoomView != null) {
                            mRoomView.addHouseMessage(roomHouseNotify);
                        }
                    }
                });
                break;
            case MessageId.roomActivityTipsNotify://直播间活动公告通知
                final RoomActivityTipsNotify roomActivityTipsNotify = JSON.parseObject(content, RoomActivityTipsNotify.class);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (getRoomId() == roomActivityTipsNotify.roomId) {
                            mRoomView.addChatMessage(roomActivityTipsNotify);
                        }
                    }
                });
            default:
                processSocketNotify(msgId, content);
                break;
        }
    }

    protected abstract void onLiveBlock(long uid);

    protected abstract void processSocketNotify(int msgId, String content);

    //获取开播封面图（分享时使用）
    protected abstract String getCoverUrl();

    //请求结束连麦
    protected void requestStopLinkMic() {
        if (mLinkMicMode) {
            mLinkMicMode = false;
            ProtoRequestHelper.task(ProtoSocketFactory.requestStopLinkMic()).request(this);
            onStopLinkMic();
        }
    }

    //结束连麦
    private void onStopLinkMic() {
        closeLinkMicClickBound();
        stopLinkMic();
    }

    protected void stopLinkMic() {
        //恢复为普通推流模式
        mLiveVideoView.hideLinkMicView();
        mLivePlayer.stopPlay();
    }

    //切换成连麦模式
    protected void changeToLinkMicMode(String nick) {
        mLinkMicMode = true;
        mLiveVideoView.showLinkMicView(isMainPublisher(), nick);
        mLivePlayer.stopPlay();
        mLivePlayer.setLinkMicUrl(mLinkMicStreamUrl);
        mLivePlayer.startPlay();

        openLinkMicClickBound();
    }

    private void stopLinkMicClick() {
        //结束连麦
        DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), getString(R.string.link_mic_stop), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestStopLinkMic();
            }
        });
    }

    //设置cocos层级
    private void setCocosViewZOrder(boolean top) {
        if (mRoomView != null) {
            if (top) {
                mRoomView.bringCocosToFront();
            } else {
                mRoomView.bringCocosToBack();
            }
        }
    }

    //设置cocos连麦小主播点击事件
    private void openLinkMicClickBound() {
        mLiveVideoView.post(new Runnable() {
            @Override
            public void run() {
                if (!isMainPublisher()) {   //小主播才有切换摄像头按钮
                    IMayCocos.setClickBound(COCOS_CLICK_ID_SWITCH_CAMERA, mLiveVideoView.getCameraView());
                }
                IMayCocos.setClickBound(COCOS_CLICK_ID_CLOSE_LINE_MIC, mLiveVideoView.getCloseView());
            }
        });
    }

    //关闭cocos连麦小主播点击事件
    protected void closeLinkMicClickBound() {
        IMayCocos.closeClickBound(COCOS_CLICK_ID_SWITCH_CAMERA);
        IMayCocos.closeClickBound(COCOS_CLICK_ID_CLOSE_LINE_MIC);
    }

    private void registerSocketNotify() {
        mSocketNotify = new IMYTBASObject(false);
        mSocketNotify.stringCommand = "SOCK_NOTIFY";
        mSocketNotify.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                processCommonSocketNotify(object.socket_msg_id, object.socket_content);
            }
        });
        mSocketNotify.addEventListenWithTBASObject();
    }

    private void registerLoginNotify() {
        mLoginNotify = new IMYTBASObject(false);
        mLoginNotify.stringCommand = EventHelper.EVENT_LOGIN_SUCCESS;
        mLoginNotify.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                onLoginSuccess();
            }
        });
        mLoginNotify.addEventListenWithTBASObject();
    }

    private void registerFollowNotify() {
        mFollowNotify = new IMYTBASObject(false);
        mFollowNotify.stringCommand = EventHelper.EVENT_FOLLOW_USER;
        mFollowNotify.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                final long uid = Long.valueOf(object.stringData);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        updateFollowAnchorView(uid, true);
                    }
                });
            }
        });
        mFollowNotify.addEventListenWithTBASObject();
    }

    private void registerUnFollowNotify() {
        mUnFollowNotify = new IMYTBASObject(false);
        mUnFollowNotify.stringCommand = EventHelper.EVENT_UN_FOLLOW_USER;
        mUnFollowNotify.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                final long uid = Long.valueOf(object.stringData);
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        updateFollowAnchorView(uid, false);
                    }
                });
            }
        });
        mUnFollowNotify.addEventListenWithTBASObject();
    }

    //禁言
    private void requestSilenceUser(long uid) {
        ProtoRequestHelper.task(ProtoSocketFactory.requestSilenceUser(mRoomId, uid)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                ToastUtil.show(RoomBaseActivity.this, R.string.tips_success_silence);
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                ErrorResult.toastError(RoomBaseActivity.this, code);
            }
        });
    }

    //踢人
    private void requestKickUser(long uid) {
        ProtoRequestHelper.task(ProtoSocketFactory.requestKickUser(mRoomId, uid)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                ToastUtil.show(RoomBaseActivity.this, R.string.tips_success_kick);
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                ErrorResult.toastError(RoomBaseActivity.this, code);
            }
        });
    }

    //举报，二次确认
    private void inform(final UserInfoCard user, final int reportCategory) {
        mReportCategory = reportCategory;
        DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), null, getString(R.string.confirm_set_inform, user.nick), new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ThreadManager.post(ThreadManager.THREAD_UI, new Runnable() {
                    @Override
                    public void run() {
                        screenShot(SCREENSHOT_REPORT);
                    }
                });
            }
        });
    }

    //举报
    private void requestReportRoom(final UserInfoCard user, int category, String imagePath) {
        //如果举报人选择的是主播，则举报房间
        if (mRoomId == user.roomId) {
            ProtoRequestHelper.task(ProtoHttpFactory.requestReportRoom(mRoomId, user.uid, category, imagePath)).setTag(this.hashCode()).request(new ProtoCallBack() {
                @Override
                public void onRequestSuccess(String command, String data) {
                    ToastUtil.show(RoomBaseActivity.this, R.string.tips_success_inform);
                }

                @Override
                public void onRequestError(String command, int code, String message) {
                    ErrorResult.toastError(RoomBaseActivity.this, code);
                }
            });
        } else { // 举报用户
            ProtoRequestHelper.task(ProtoHttpFactory.requestReportUser(user.uid, category, imagePath)).setTag(this.hashCode()).request(new ProtoCallBack() {
                @Override
                public void onRequestSuccess(String command, String data) {
                    ToastUtil.show(RoomBaseActivity.this, R.string.tips_success_inform);
                }

                @Override
                public void onRequestError(String command, int code, String message) {
                    ErrorResult.toastError(RoomBaseActivity.this, code);
                }
            });
        }
    }

    protected void processPopupMenuClick(int action) {
        switch (action) {
            case MENU_ACTION_INFORM://举报
                //显示举报类型菜单
                DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), PopupMenuFragment.newInstance(mReportCategoryMenuList));
                break;
            case MENU_ACTION_SILENCE:   //禁言
                DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), null, getString(R.string.confirm_silence, mMenuActionUser.nick), new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        requestSilenceUser(mMenuActionUser.uid);
                    }
                });
                break;
            case MENU_ACTION_KICK:  //踢人
                DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), null, getString(R.string.confirm_kick, mMenuActionUser.nick), new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        requestKickUser(mMenuActionUser.uid);
                    }
                });
                break;
            case MENU_ACTION_BLACK:
                break;
            //举报类型
            case MENU_ACTION_REPORT_OBSCENE:
                inform(mMenuActionUser, ReportCategory.Obscene);
                break;
            case MENU_ACTION_REPORT_FRAUD:
                inform(mMenuActionUser, ReportCategory.Fraud);
                break;
            case MENU_ACTION_REPORT_VIOLENCE:
                inform(mMenuActionUser, ReportCategory.Violence);
                break;
            case MENU_ACTION_REPORT_DRUG:
                inform(mMenuActionUser, ReportCategory.DrugOrGambling);
                break;
            case MENU_ACTION_REPORT_UNLIKE:
                inform(mMenuActionUser, ReportCategory.Unlike);
                break;
        }
    }

    protected abstract void showAdminMenu(UserInfoCard userInfoCard);

    protected void shareRoom() {
        if (mAnchorInfo != null) {
            String image = getCoverUrl();
            String url = UrlHelper.getShareLiveUrl(mAnchorInfo.roomId);
            String title = getString(R.string.live_share_title, mAnchorInfo.nick);
            String des = getString(R.string.live_share_des, mAnchorInfo.nick);
            DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), ShareDialogFragment.newInstance(ShareDialogFragment.WEB, url, title, des, image));
        }

    }

    private void requestAnchorDeviceInfo() {
        ProtoRequestHelper.task(ProtoHttpFactory.requestRoomDeviceInfo(mRoomId)).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                Result<DeviceInfoModel> result = JSON.parseObject(data, new TypeReference<Result<DeviceInfoModel>>() {
                }.getType());
                if (result.data != null) {
                    if (!isDestroyed()) {
                        DialogFragmentHelper.showTipsDialog(getSupportFragmentManager(), result.data.getInfo());
                    }
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        //重新检查摄像头权限
        if (mWaitCheckCameraPermission) {
            mWaitCheckCameraPermission = false;
            checkPermissionAndStartPreview();
        }

        if (mStartPush && mPausePush) {
            mPausePush = false;
            //恢复推流
            if (mLivePusher != null) {
                mLivePusher.resumePusher();
            }
            if (isMainPublisher() && isNeedSendPushStatus()) {    //大主播才设置直播状态
                ProtoRequestHelper.task(ProtoSocketFactory.requestSetLiveResume()).request(null);
            }
        }
        //恢复播放
        if (mLivePlayer != null && mPausePlay) {
            mPausePlay = false;
            mLivePlayer.resume();
        }
        if (NetworkUtil.isGNetwork(this)) {
            TSnackbar.make(getDecorView(), getString(R.string.tip_network_mobile)).setDuration(TSnackbar.LENGTH_LONG).show();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mLivePlayer != null) {
            mPausePlay = true;
            mLivePlayer.pause();
        }

        if (mStartPush) {
            if (mLivePusher != null) {
                mPausePush = true;
                mLivePusher.pausePusher();
            }
            if (isMainPublisher() && isNeedSendPushStatus()) {
                ProtoRequestHelper.task(ProtoSocketFactory.requestSetLivePause()).request(null);
            }
        }
    }

    @Override
    public void onDestroy() {
        requestStopLinkMic();

        if (mLivePusher != null) {
            mLivePusher.onDestroy();
        }

        if (mRotationObserver != null) {
            mRotationObserver.stopObserver();
        }

        if (mSocketNotify != null) {
            mSocketNotify.destroy();
        }
        if (mLoginNotify != null) {
            mLoginNotify.destroy();
        }
        if (mFollowNotify != null) {
            mFollowNotify.destroy();
        }
        if (mUnFollowNotify != null) {
            mUnFollowNotify.destroy();
        }

        if (mLivePlayer != null) {
            mLivePlayer.onDestroy();
        }

        cocosExitRoom();
        IMayCocosNetManager.getInstance().removeOnCocosRoomListener(this);
        NetworkHelper.getInstance().removeListener(this);
        super.onDestroy();
        UMShareAPI.get(this).release();
    }

    @Override
    public void onBackPressed() {
        if (isDestroyed()) {
            return;
        }
        if (mRoomView != null && mRoomView.onBackPressed()) {
            return;
        }
        if (!mCocosAllowClose) {
            return;
        }
        cocosExitRoom();
        removeCocosView();
        super.onBackPressed();

        ActivityStackManager.getInstance().clearAll();
    }

    @Override
    public void finish() {
        cocosExitRoom();
        super.finish();
    }

    @Override
    public void onMenuClick(int action) {
        processPopupMenuClick(action);
    }

    protected void cocosExitRoom() {
        if (!mCocosExitRoom) {
            mCocosExitRoom = true;
            cocosExitRoomByType();
        }
    }

    protected abstract void cocosExitRoomByType();

    protected void followUser(long uid, CallBack callBack) {
        requestFollowUser(uid, callBack);
        if (!mHasFollowed && mAnchorInfo != null && uid == mAnchorInfo.uid) {
            ProtoRequestHelper.task(ProtoSocketFactory.requestLikeFollow(getRoomId(), true)).setTag(this.hashCode()).request(this);
            mHasFollowed = true;
        }
    }

    @Override
    public void onCloseClick() {
        onBackPressed();
    }

    @Override
    public void onSendClick(long uid, String content) {
        if ("#vankaoio".equalsIgnoreCase(content)) { //查看主播信息指令
            requestAnchorDeviceInfo();
        } else {
            //聊天
            ProtoRequestHelper.task(ProtoSocketFactory.requestRoomChat(getRoomId(), uid, content)).request(new ProtoCallBack() {
                @Override
                public void onRequestSuccess(String command, String data) {

                }

                @Override
                public void onRequestError(String command, int code, String message) {
                    if (!isDestroyed()) {
                        ErrorResult.toastError(RoomBaseActivity.this, code);
                    }
                }
            });
        }
    }

    @Override
    public void onUserClick(UserInfoCard userInfo) {
        showUserInfoCard(userInfo);
    }

    @Override
    public void onNotifyJumpClick(String command) {
        H5Helper.startActivity(command, this);
    }

    @Override
    public void onFollowClick(long uid) {
        followUser(uid, null);
    }

    @Override
    public void onLoadMoreUser(int page) {
        requestLoadMoreUser(page);
    }

    @Override
    public void onKeyboardShowing(boolean isShowing, int width, int height) {
        //通知cocos软键盘状态
        IMayCocos.setKeyboardStatus(isShowing, width, height);
    }

    @Override
    public void onAdminMenuClick(UserInfoCard userInfoCard) {
        mMenuActionUser = userInfoCard;
        showAdminMenu(userInfoCard);
    }

    @Override
    public void onUserMenuClick(UserInfoCard userInfoCard) {
        mMenuActionUser = userInfoCard;
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), PopupMenuFragment.newInstance(mInformMenuList));
    }

    @Override
    public void onRankingClick() {
        //显示7天礼物排行
        RoomRankingActivity.startActivity(this, mRoomId, mAnchorInfo.uid == AccountManager.getInstance().getUid());
    }

    //资料卡，点击at
    @Override
    public void onAtClick(UserInfoCard userInfoCard) {
        mRoomView.setAtUser(userInfoCard);
    }

    @Override
    public void onGiftClick(UserInfoCard user) {
        //资料卡，主播送礼给观众
        if (mAnchorInfo != null && user.uid != mAnchorInfo.uid) {
            IMayCocos.showGiftPanel(user);
        } else {    //给主播送礼
            IMayCocos.showGiftPanel();
        }
    }

    @Override
    public void onNetworkChange(int networkType) {
        TSnackbar snackbar = null;
        if (networkType == NetworkUtil.G_NETWORK) {
            snackbar = TSnackbar.make(getDecorView(), getString(R.string.tip_network_mobile));
        } else if (networkType == NetworkUtil.NO_NETWORK) {
            snackbar = TSnackbar.make(getDecorView(), getString(R.string.tip_network_no));
        }
        if (snackbar == null) {
            return;
        }
        final TSnackbar.SnackbarLayout snackbarView = (TSnackbar.SnackbarLayout) snackbar.getView();
        snackbarView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        snackbar.show();
    }

    @Override
    public void onPlayBegin() {

    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onPlayEnd() {

    }

    @Override
    public void onPlayReconnect(int count) {

    }

    @Override
    public void onPlayProgress(int progress, int duration) {

    }

    @Override
    public void onCocosShowBottomView(boolean show) {
        //cocos显示或隐藏底部view
        mRoomView.setBottomViewVisibility(show);
    }

    @Override
    public void onCocosShowTopView(boolean show) {
        //cocos显示或隐藏顶部view（不包括水印）
        mRoomView.setTopViewVisibility(show);
    }

    @Override
    public void onCocosShowActionView(boolean show) {
        //cocos显示或隐藏底部菜单
        mRoomView.setActionViewVisibility(show);
    }

    @Override
    public void onCocosBalanceNotEnough() {
        //cocos显示余额不足
        DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), null, getString(R.string.balance_not_enough), getString(R.string.button_recharge), null, false, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RechargeActivity.start(RoomBaseActivity.this);
            }
        }, null);
    }

    @Override
    public void onCocosRechargeClick() {
        //cocos点击充值
        RechargeActivity.start(RoomBaseActivity.this);
    }

    @Override
    public void onCocosChooseUserClick() {
        //cocos选择人
        List<UserInfoCard> userList = new ArrayList<>();
        for (UserInfoCard user : mRoomView.getUserData()) {
            if (user.uid != AccountManager.getInstance().getUid()) {    //过滤自己
                userList.add(user);
            }
        }
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), ChooseUserFragment.newInstance(userList));
    }

    @Override
    public void onCocosShowUserInfo(UserInfoCard userInfo) {
        //cocos显示用户资料卡
        showUserInfoCard(userInfo);
    }

    @Override
    public void onCocosSetBottomMargin(int margin) {
        //cocos设置底部margin
        mRoomView.setBottomMargin(margin);
    }

    @Override
    public void onCocosChangeHierarchy(boolean top) {
        //cocos层级
        setCocosViewZOrder(top);
    }

    @Override
    public void onCocosShowGameButton(boolean show, boolean up) {
        //cocos显示游戏隐藏按钮
    }

    @Override
    public void onCocosClickBound(int id) {
        //cocos点击透传
        switch (id) {
            case COCOS_CLICK_ID_CLOSE_LINE_MIC:
                stopLinkMicClick();
                break;
            case COCOS_CLICK_ID_SWITCH_CAMERA:
                switchCamera();
                break;
        }
    }

    @Override
    public void onCocosGetRoomData() {
        //cocos获取房间数据
        IMayCocos.reTryEnterRoom();
    }

    @Override
    public void onCocosShowGiftRedPoint(boolean visible) {
        //cocos显示礼物图标红点
        mRoomView.setGiftRedPointViewVisible(visible);
    }

    @Override
    public void onCocosSetHorizontalScrollEnabled(boolean enabled) {
        //cocos设置是否允许垂直滚动
    }

    @Override
    public void onCocosSetVerticalScrollEnabled(boolean enabled) {
        //cocos设置是否允许水平滚动
    }

    //弹出首充
    @Override
    public void onCocosShowFirstRecharge() {
        showFirstRechager();

    }

    @Override
    public void onChooseUser(UserInfoCard user) {
        //送礼选人
        IMayCocos.showGiftPanel(user);
    }

    @Override
    public void onPushNetBusy() {
//        TSnackbar.make(getDecorView(), getString(R.string.tip_network_busy)).show();
//        ProtoRequestHelper.task(ProtoSocketFactory.requestSetLiveBusy()).request(this);
    }

    @Override
    public void onPushOpenCameraFail() {
        DialogFragmentHelper.showTipsDialog(getSupportFragmentManager(), getString(R.string.live_room_error_camera), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onPushOpenMicFail() {
        DialogFragmentHelper.showTipsDialog(getSupportFragmentManager(), getString(R.string.live_room_error_mic), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onPushDecodeFail() {
        if (mRoomView != null) {
            mRoomView.showLiveStatusTips(getString(R.string.live_room_error_other));
        }
    }

    @Override
    public void onPushNetDisconnect() {
        if (mRoomView != null) {
            mRoomView.showLiveStatusTips(getString(R.string.live_room_error_network));
        }
    }

    @Override
    public void onPushBegin() {
        if (mRoomView != null) {
            mRoomView.hideLiveStatusTips();
        }
    }

    @Override
    public LivePlayer getLivePlayer() {
        return mLivePlayer;
    }

    //检查摄像头权限并开启预览
    protected void checkPermissionAndStartPreview() {
        //摄像头权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                showCameraPermissionDialog();
            } else {
                // 请求相机权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE_CAMERA);
            }
            return;
        }

        //麦克风权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
                showAudioRecordPermissionDialog();
            } else {
                // 请求麦克风权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSION_REQUEST_CODE_AUDIO_RECORD);
            }
            return;
        }
        if (mLivePusher != null) {
            mLivePusher.startPreview(decodeResource(getWatermark()));
        }
    }

    @Override
    public void onCocosSetLiveCloseEvent(boolean allowClose) {
        this.mCocosAllowClose = allowClose;
        if (!allowClose) {  //1秒恢复
            if (mResumeAllowCloseRunnable == null) {
                mResumeAllowCloseRunnable = new Runnable() {
                    @Override
                    public void run() {
                        mCocosAllowClose = true;
                    }
                };
            }
            ThreadManager.postDelayed(ThreadManager.THREAD_UI, mResumeAllowCloseRunnable, 500);
        } else {
            ThreadManager.removeRunnable(mResumeAllowCloseRunnable);
        }
    }

    //推流水印
    protected int getWatermark() {
        return 0;
    }


    private Bitmap decodeResource(int id) {
        if (id == 0) {
            return null;
        }
        TypedValue value = new TypedValue();
        getResources().openRawResource(id, value);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inTargetDensity = value.density;
        return BitmapFactory.decodeResource(getResources(), id, opts);
    }

    private void showCameraPermissionDialog() {
        showCameraPermissionDialog(getString(R.string.permission_camera_title), getString(R.string.permission_camera));
    }

    private void showAudioRecordPermissionDialog() {
        showCameraPermissionDialog(getString(R.string.permission_audio_record_title), getString(R.string.permission_audio_record));
    }

    //显示摄像头权限对话框
    private void showCameraPermissionDialog(String title, String message) {
        DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), title, message,
                getString(R.string.permission_button_setting), null, false, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //activity恢复后是否再次检查权限
                        mWaitCheckCameraPermission = true;
                        AppUtil.startInstalledAppDetailsActivity(RoomBaseActivity.this);
                    }
                },
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isMainPublisher()) {
                            onBackPressed();
                        }
                    }
                });
    }

//    private void showLocationPermissionDialog(String title, String message) {
//        DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), title, message,
//                getString(R.string.permission_button_setting), null, false, new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        //activity恢复后是否再次检查权限
//                        mWaitCheckLocalPermission = true;
//                        AppUtil.startInstalledAppDetailsActivity(RoomActivity.this);
//                    }
//                }, null);
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE_CAMERA:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 用户允许
                    checkPermissionAndStartPreview();
                } else {
                    // 用户拒绝
                    showCameraPermissionDialog();
                }
                break;
            case PERMISSION_REQUEST_CODE_AUDIO_RECORD:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 用户允许
                    checkPermissionAndStartPreview();
                } else {
                    // 用户拒绝
                    showAudioRecordPermissionDialog();
                }
                break;
//            case PERMISSION_REQUEST_CODE_LOCATION:
//                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    // 用户允许，开启定位
//                    mShowLocation = true;
//                    setLocationStatus();
//                }
//                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        onActivityRotation();
    }

    /**
     * 判断Activity是否可旋转。只有在满足以下条件的时候，Activity才是可根据重力感应自动旋转的。
     * 系统“自动旋转”设置项打开；
     *
     * @return false---Activity可根据重力感应自动旋转
     */
    protected boolean isActivityCanRotation() {
        // 判断自动旋转是否打开
        int flag = Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
        if (flag == 0) {
            return false;
        }
        return true;
    }

    private void onActivityRotation() {
        if (mLivePusher != null) {
            mLivePusher.onActivityRotation(getWindowManager().getDefaultDisplay().getRotation());
        }
    }

    //观察屏幕旋转设置变化，类似于注册动态广播监听变化机制
    private class RotationObserver extends ContentObserver {
        ContentResolver mResolver;

        public RotationObserver(Handler handler) {
            super(handler);
            mResolver = getContentResolver();
        }

        //屏幕旋转设置改变时调用
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            //更新按钮状态
            if (isActivityCanRotation()) {
                onActivityRotation();
            } else {
//                mPortrait = true;
                if (mLivePusher != null) {
                    mLivePusher.setHomeDownOrientation();
                }
            }

        }

        public void startObserver() {
            mResolver.registerContentObserver(Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), false, this);
        }

        public void stopObserver() {
            mResolver.unregisterContentObserver(this);
        }
    }

    @CallSuper
    @Override
    protected void onActivityResult(int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCREEN_SHOT_REPOST || requestCode == REQUEST_CODE_SCREEN_SHOT) {
            final int status = requestCode == REQUEST_CODE_SCREEN_SHOT_REPOST ? SCREENSHOT_REPORT : SCREENSHOT_SHARE;
            if (resultCode == RESULT_OK) {
                if (System.currentTimeMillis() - mScreenShotTime > 300) {
                    ThreadManager.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            processScreenShot(resultCode, data, status);
                        }
                    }, 300);
                } else {
                    processScreenShot(resultCode, data, status);
                }
            }
        }
    }

    protected void screenShot(int stauts) {
        if (isAlreadyOneScreenshotTask()) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (mMediaProjectionManager == null) {
                mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
                DisplayMetrics outMetric = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(outMetric);
                mWidth = outMetric.widthPixels;
                mHeight = outMetric.heightPixels;
                mScreenDensity = (int) outMetric.density;
            }
            mScreenShotTime = System.currentTimeMillis();
            Intent intent = new Intent(mMediaProjectionManager.createScreenCaptureIntent());
            try {
                if (stauts == SCREENSHOT_SHARE) {
                    startActivityForResult(intent, REQUEST_CODE_SCREEN_SHOT);   //部分手机可能崩溃
                } else if (stauts == SCREENSHOT_REPORT) {
                    startActivityForResult(intent, REQUEST_CODE_SCREEN_SHOT_REPOST);
                }
            } catch (Throwable r) {
                r.printStackTrace();
                CrashReport.postCatchedException(r);
            }
        } else {
            ToastUtil.show(this, R.string.sceenshot_share_focus);
        }
    }

    private void processScreenShot(int resultCode, Intent data, final int status) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                if (!isCurrentActivity()) {
                    return;
                }
                onScreenshotTaskBegan();
                final MediaProjection mediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
                ImageReader imageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 1);
                final VirtualDisplay virtualDisplay = mediaProjection.createVirtualDisplay("VankaScreenShot", mWidth, mHeight,
                        mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, imageReader.getSurface(), null, null);
                imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
                    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onImageAvailable(ImageReader imageReader) {
                        Image image = null;
                        try {
                            //当前activity才截屏
                            if (isCurrentActivity()) {
                                image = imageReader.acquireLatestImage();
                                if (image != null) {
                                    final Image.Plane[] planes = image.getPlanes();
                                    if (planes.length > 0) {
                                        final ByteBuffer buffer = planes[0].getBuffer();
                                        int pixelStride = planes[0].getPixelStride();
                                        int rowStride = planes[0].getRowStride();
                                        int rowPadding = rowStride - pixelStride * mWidth;

                                        Bitmap bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.ARGB_8888);
                                        bitmap.copyPixelsFromBuffer(buffer);

                                        Bitmap croppedBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight);

                                        final String path = saveBitmap(croppedBitmap);// 保存图片

                                        if (status == SCREENSHOT_SHARE) {
                                            shareScreen(path);
                                        } else if (status == SCREENSHOT_REPORT) {
                                            UploadFileManager.getInstance().uploadHead(path, new UploadFileManager.UploadCallBack() {
                                                @Override
                                                public void uploadSuccess(String fileUrl) {
                                                    requestReportRoom(mMenuActionUser, mReportCategory, fileUrl);
                                                    onScreenshotTaskOver();
                                                }

                                                @Override
                                                public void uploadFailer(int errorCode, String errorMessage) {
                                                    requestReportRoom(mMenuActionUser, mReportCategory, null);
                                                    onScreenshotTaskOver();
                                                }
                                            });
                                        }

                                        if (croppedBitmap != null) {
                                            croppedBitmap.recycle();
                                        }
                                        if (bitmap != null) {
                                            bitmap.recycle();
                                        }

                                        onScreenshotTaskOver();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (image != null) {
                                image.close();
                            }
                            if (imageReader != null) {
                                imageReader.close();
                            }
                            if (virtualDisplay != null) {
                                virtualDisplay.release();
                            }

                            imageReader.setOnImageAvailableListener(null, null);
                            mediaProjection.stop();
                        }
                    }
                }, getBackgroundHandler());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (status == SCREENSHOT_REPORT) {
                requestReportRoom(mMenuActionUser, mReportCategory, null);
            }
        }
    }

    private void shareScreen(final String path) {
        ThreadManager.post(ThreadManager.THREAD_UI, new Runnable() {
            @Override
            public void run() {
                ScreenshotFragment fragment = ScreenshotFragment.newInstance(path);
                DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), fragment);
            }
        });
    }

    private String saveBitmap(Bitmap bitmap) throws IOException {
        File file = ICUtils.getOutputMediaFile(this);
        OutputStream outputStream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
        outputStream.flush();
        outputStream.close();
        try {
            MediaStore.Images.Media.insertImage(getContentResolver(),
                    file.getAbsolutePath(), file.getName(), null);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    private boolean isCurrentActivity() {
        return !isDestroyed() && !ActivityHelper.getInstance().isBackground() && ActivityHelper.getInstance().getCurrentActivity() instanceof RoomBaseActivity;
    }

    private boolean isAlreadyOneScreenshotTask() {
        return oneScreenshot.get() == 1;
    }

    private synchronized void onScreenshotTaskBegan() {
        oneScreenshot.set(1);
    }

    private synchronized void onScreenshotTaskOver() {
        oneScreenshot.set(0);
    }

    private Handler getBackgroundHandler() {
        if (mBackgroundHandler == null) {
            HandlerThread backgroundThread = new HandlerThread("screenshot", android.os.Process.THREAD_PRIORITY_BACKGROUND);
            backgroundThread.start();
            mBackgroundHandler = new Handler(backgroundThread.getLooper());
        }

        return mBackgroundHandler;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }

    @Override
    public void onFailCallBack(String message) {
        TSnackbar.make(getDecorView(), message).show();
    }

    @Override
    public void onSuccessCallBack(String message) {
        if (!mHasShared) {
            ProtoRequestHelper.task(ProtoSocketFactory.requestLikeShare(getRoomId(), true)).setTag(this.hashCode()).request(this);
            mHasShared = true;
        }
        TSnackbar.make(getDecorView(), message).show();
    }

    @Override
    public void onCocosShowH5Event(CocosOpenWebViewModel model) {
        WebViewActivity.startActivity(this, model.getTitle(), model.getUrl() + "?uid=" + AccountManager.getInstance().getUid());
    }


    // 首充
    private void showFirstRechager() {
        ProtoRequestHelper.task(ProtoHttpFactory.getSysparam(CONFIG_VALUE_RECHARGE_TIP_URL2)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                Result<SysparamModel> result = JSON.parseObject(data, new TypeReference<Result<SysparamModel>>() {
                }.getType());
                ImayLogUtil.log("FirstRecharge", data);
                    if (result.result == CodeSuccess && !StringUtil.isEmpty(result.data.getStringValue())) {
//                    if (result.result==CodeSuccess ){
                        AdsModel adsModel = new AdsModel();
                        adsModel.setPhoto(result.data.getStringValue());
//                        adsModel.setPhoto("http://odfjym91z.bkt.clouddn.com/rbt/w1347.jpg");
                        adsModel.setJumpContent("imay://com.imay.live/openwith?type=4");
                        ShowAdsFragment fragment = ShowAdsFragment.newInstance(adsModel);
                        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), fragment);
                    }
                }

            @Override
            public void onRequestError(String command, int code, String message) {

            }

        });


    }

}
